package click
import grails.converters.*
import java.util.Calendar


class ApiController {

    def index = { // 0 skip ,1 ok , 10 ,manager
        log.info( "api index params.id = ${params.id}") 
        Machine mac = Machine.findByMac(params.id ,  [cache:false])
        if (!mac) {
            return render("0")
        }
 
        if (!params.ip) {
            String ip = request.getHeader("x-forwarded-for");       
            if(!ip   || "unknown".equalsIgnoreCase(ip)) {       
                ip = request.getHeader("Proxy-Client-IP");       
            }       
            if(!ip || "unknown".equalsIgnoreCase(ip)) {       
                ip = request.getHeader("WL-Proxy-Client-IP");       
            }       
            if(!ip || "unknown".equalsIgnoreCase(ip)) {       
                ip = request.getRemoteAddr();       
            }       
            params.ip = ip; 
        }
        log.info( "api index params.ip = ${params.ip}") 

        if (mac.manage) {
            new Ip(source : params.id , address: params.ip , success : false).save() 
            return render("2")
        }

        def count = Ip.lastIp(params.ip.toString())
        log.info( "api index Ip.lastIp = ${count}")  

        new Ip(source : params.id , address: params.ip , success : count == 0).save() 
        render(count == 0 ? '1' : '0')
     
        
    }
 

    def website = { 
        def  result = []
        def ws = Website.list(sort:"ad", order:"asc") 
        log.info("Website total : ${ws.size()}")
        
        Calendar   calendar   =   Calendar.getInstance();
        def int now_hour = calendar.get(Calendar.HOUR_OF_DAY)

       
        //def pass 
        // 循环站点，并找出可以执行的任务
        // 站点可以用两种方式限制访问的次数和频率
        // 一种是设置HourRate，设置每个小时可以点击的次数。
        // 第二种是在一个website下设置多个Task，这样每个Task根据自己的权重，都有机会被执行。
        // 也可以两种一起设置。
        ws.each{ website ->
            /////////// 通过HourRate判断这个Website可不可以执行
            //pass = true
            if (website.dayOfhit != now_hour) {// 新的小时，清零计数器
                website.total = 0
            }
            
            log.info(website.dayOfhit +"||"+ now_hour);
 
            ///////  返回task
            //log.info(website.name + " pass = " + pass);
            if (website.rateMatch()) {
                def json = Task.selectTasks(website)
                if (json) {
                    result.add(json);
                } 
            }

            website.dayOfhit = now_hour
            //log.info(website.name + "save to :" + website.save(flush:true))
            if (!website.save(flush:true)) {
                website.errors.each {
                    log.info it
                } 
            }
            
        } 
      
        //return render(result as JSON) 
        if (result.size() == 0) {
            render(contentType:"text/json",text : "[\"sleep,${60*5}\"]")  
        }else{
            render(contentType:"text/json",text : "[${result.join(',')}]")  
        }
    }
    static String version = "Givenchy 0.2";
    static String updateURL = "";

    def update = {
       render( "${ApiController.version}|${ApiController.updateURL}")
    }
}
